import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import Link from 'umi/link';
import { Row, Col, Card, Icon, Button, Popconfirm, message, Divider, Form, Input} from "antd";
import StandardTable from '../../../components/StandardTable';
import Upload from "../../../components/Upload";
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';
// const FormItem = Form.Item;
// const { Option } = Select;
// const OptionAuto = AutoComplete.Option;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');



@connect(({ equipment_maintain, loading }) => ({
  resdata: equipment_maintain.resdata,
  loading: equipment_maintain.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {
    const { pageSize } = this.state;
    // 列表
    this.getDataList({},pageSize,1);
  }

  componentWillReceiveProps(nextProps) {
    // 外层发起刷新数据请求
    if (nextProps.isReloadList === true && this.props.isReloadList === false) {
      const { pageSize } = this.state;
      this.getDataList({},pageSize,1);
      this.props.sotpReloadList();
    }
  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch, pagesquery } = this.props;
    dispatch({
      type: 'equipment_maintain/fetch_maintain_list',
      payload: {
        pageSize,
        currentPage,
        ...pagesquery,
        ...params
      },
    });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.maintenanceId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };



  // 批量删除
  handleActionList = (type,id) => {
    const { dispatch } = this.props;
    const { selectedRows,formValues, pageSize, currentPage } = this.state;
    if(!id && !selectedRows && selectedRows.length<1) return;
    const maintenanceIds = id ? [id] : selectedRows;

    switch (type) {
      case '3':
        dispatch({
          type: 'equipment_maintain/action_maintain_del',
          payload: {
            maintenanceIds,
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("所选备件已删除")
        }).then(()=>{
          this.getDataList(formValues,pageSize,currentPage);
        });
        break;
      case '4':
        dispatch({
          type: 'equipment_maintain/action_maintain_export',
          payload: {
            maintenanceIds,
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("备件导出成功")
        });
        break;

      default:

        break;
    }
  };

  // 批量导入
  handleBatchImport = info => {
    let fileList = info.fileList;
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    if (info.file.status == "done") {
      fileList = fileList.map(item => {
        if (item.response && item.response.error_no != "0") {
          item.status = "error";
        }
        return item;
      });


      if(info.file && info.file.response && info.file.response.data && info.file.response.data.token){
        dispatch({
          type: 'equipment_maintain/action_maintain_import',
          payload: {
            file_url:info.file.response.data.token,
          },
        }).then(()=>{
          message.success("文件导入成功")
        }).then(()=>{
          this.getDataList(formValues,pageSize,1);
        });
      }

    }


  };

  // 新增model传导-------------------
  handleAddModel = (e) =>{
    this.props.addModelCallBack(e);
  }
  handleDetailModel= (detailInfoId,detailInfoName) =>{
    const { dispatch } = this.props;
    const { formValues, currentPage} = this.state;
    router.push({ pathname:`/equipment/maintenance/${detailInfoId}`,  query: { ...formValues, currentPage} });

  }



  render() {

    const { resdata, loading } = this.props;
    const { selectedRows } = this.state;


    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        fixed: 'left',
        render: (text, row, index)=> (
          <span>{index+1}</span>
        ),
      },
      {
        title: '单位名称',
        dataIndex: 'maintenanceName',
      },
      {
        title: '地址',
        dataIndex: 'mainAddress',
      },
      {
        title: '联系人',
        dataIndex: 'linkman',
      },
      {
        title: '联系电话',
        dataIndex: 'phone',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
      },
      {
        title: '操作',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={'10033'} >
              <a onClick={() => this.handleDetailModel(row.maintenanceId, row.maintenanceName)}>详情</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10034'} >
              <a onClick={() => this.handleAddModel(row.maintenanceId)}>修改</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10035'} >
              <Popconfirm title="是否确定要删除?" onConfirm={() => this.handleActionList("3",row.maintenanceId)}  okText="是" cancelText="否">
                <a >删除</a>
              </Popconfirm>
            </Authorized>
          </Fragment>
        ),
      },
    ];




    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListOperator}>
            <Authorized authority={'10032'} >
              <Button icon="plus" type="primary"  onClick={() => this.handleAddModel(0)}>
                新建
              </Button>
            </Authorized>
{/*            <Authorized authority={'10036'} >
              <Upload showUploadList={false} onChange={this.handleBatchImport}>
                <Button icon="plus" type="primary" >
                  批量导入
                </Button>
              </Upload>
            </Authorized>*/}

            <Authorized authority={'10037'} >
              <Popconfirm title="是否确定要批量删除?" onConfirm={() => this.handleActionList("3")}  okText="是" cancelText="否">
                <Button icon="minus" type="default" disabled={selectedRows.length > 0 ? false : true}>
                  批量删除
                </Button>
              </Popconfirm>
            </Authorized>
{/*            <Authorized authority={'10038'} >
              <Button type="default" onClick={() => this.handleActionList("4")} disabled={selectedRows.length > 0 ? false : true}>
                导出
              </Button>
            </Authorized>*/}

          </div>
          <StandardTable
            selectedRows={selectedRows}
            rowKey="maintenanceId"
            // scroll={{ x: 1500 }}
            loading={loading.reslist}
            data={resdata}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
